package com.patchmanage.back.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.patchmanage.back.entity.AlarmConfig;
import com.patchmanage.back.service.IAlarmConfigService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

@Api(value="邮件发送 controller",tags={"邮件发送"})
@RestController
@RequestMapping("/back/mail")
public class  MailController {

    @Autowired
    public IAlarmConfigService alarmConfigService;


    /**
     * 发送邮件
     * @return
     */
    @PostMapping("/sendMail")
    public String sendSingleMail(@ApiIgnore  @RequestBody Dict dict){

        AlarmConfig alarmConfig = alarmConfigService.getById(1);
        String emailAlarmConfig =alarmConfig.getEmailAlarmConfig();
        JSONObject jsonObject = JSONUtil.parseObj(emailAlarmConfig);

        MailAccount account = new MailAccount();
        account.setHost(jsonObject.getStr("emailServerUrl"));
        account.setPort(jsonObject.getInt("host"));
        account.setAuth(true);
        account.setFrom(jsonObject.getStr("fromUser"));
        account.setUser(jsonObject.getStr("fromUser"));
        account.setPass(jsonObject.getStr("password"));
        String toUser = jsonObject.getStr("toUser");
        return MailUtil.send(account,CollUtil.newArrayList(toUser.split(",")), "测试标题", "测试邮件", false);
    }

}